<template>
  <div class="image-upload-container">
    <!-- 图片预览区域 -->
    <div v-for="(image, index) in imagePreviews" :key="index" class="image-preview-wrapper">
      <div class="image-preview" @mouseover="hoverIndex = index" @mouseleave="hoverIndex = null">
        <img :src="image" alt="Preview" class="preview-image" />
        <button v-if="hoverIndex === index" @click="removeImage(index)" class="delete-button">×</button>
      </div>
    </div>

    <!-- 上传按钮 -->
    <label class="upload-button">
      <input type="file" multiple @change="handleFileChange" style="display: none;" />
      +
    </label>
  </div>
</template>

<script>
export default {
  name: 'ImageUpload',
  props: {
    // 接收父组件传递的图片数据
    images: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      imagePreviews: this.images, // 使用父组件传递的数据初始化
      hoverIndex: null, // 当前悬停的图片索引
    };
  },
  watch: {
    // 监听父组件传递的 images 数据变化
    images(newImages) {
      this.imagePreviews = newImages;
    },
  },
  methods: {
    // 处理文件选择
    handleFileChange(event) {
      const files = event.target.files;
      if (files) {
        for (let i = 0; i < files.length; i++) {
          const file = files[i];
          if (file.type.startsWith('image/')) {
            const reader = new FileReader();
            reader.onload = (e) => {
              this.imagePreviews.push(e.target.result);
              this.emitImagesUpdate(); // 更新父组件数据
            };
            reader.readAsDataURL(file);
          }
        }
      }
    },

    // 删除图片
    removeImage(index) {
      this.imagePreviews.splice(index, 1);
      this.emitImagesUpdate(); // 更新父组件数据
    },

    // 向父组件发送更新后的图片数据
    emitImagesUpdate() {
      this.$emit('update:images', this.imagePreviews);
    },
  },
};
</script>

<style scoped>
/* 样式保持不变 */
.image-upload-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.image-preview-wrapper {
  position: relative;
  width: 50px;
  height: 50px;
}

.image-preview {
  width: 100%;
  height: 100%;
  position: relative;
  border: 1px solid #ccc;
  border-radius: 4px;
  overflow: hidden;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.delete-button {
  position: absolute;
  top: 2px;
  right: 2px;
  background: rgba(255, 0, 0, 0.7);
  border: none;
  color: white;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
}

.upload-button {
  width: 50px;
  height: 50px;
  border: 1px dashed #ccc;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: #666;
  cursor: pointer;
}

.upload-button:hover {
  border-color: #999;
  color: #333;
}
</style>